package demos;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Enumeration;
import java.security.cert.Certificate;
import java.security.Key;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class DemoLlaves {

    public static void main(String[] args) {

        KeyStore keyStore;
        KeyFactory keyFactory = null;

        try {
            //String home = System.getProperty("user.home");
            FileInputStream file_inputstream = new FileInputStream("c:/temp/Administrador.p12");
            
            keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(file_inputstream, "compartir".toCharArray());
            System.out.println("Keystore size " + keyStore.size());
            Enumeration aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                System.out.println(aliases.nextElement());
            }
            Key key = keyStore.getKey("Administrador", "compartir".toCharArray());
            System.out.println("Key information " + key.getAlgorithm() + " "
                    + key.getFormat());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
            keyFactory = keyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

            Certificate cert = keyStore.getCertificate("Administrador");
            //X509EncodedKeySpec keySpec1 = new X509EncodedKeySpec(cert.getPublicKey().getEncoded());
            //PublicKey publicKey = keyFactory.generatePublic(keySpec1);
            PublicKey publicKey = cert.getPublicKey();

            String testString = "A string to be encoded";

            Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            rsaCipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] encodedBytes = rsaCipher.doFinal(testString.getBytes());
            System.out.println("Encoded byte array length = "
                    + encodedBytes.length + "\nFirst 20 bytes = ");
            for (int i = 0; i < 20; i++) {
                System.out.print(encodedBytes[i] + " ");
            }
            System.out.println();

            rsaCipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] decodedBytes = rsaCipher.doFinal(encodedBytes);
            String output = new String(decodedBytes);
            System.out.println("String after RSA encryption and decryption = "
                    + output);

        } catch (Exception e) {
            System.err.println("Exception:- " + e);
        }
    }
}
